"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  ArrowLeft,
  TrendingUp,
  Search,
  BarChart3,
  PieChart,
  DollarSign,
  Target,
  AlertTriangle,
  CheckCircle,
} from "lucide-react"

export default function MarketAnalyzerPage() {
  const router = useRouter()
  const [selectedIndustry, setSelectedIndustry] = useState("")
  const [selectedRegion, setSelectedRegion] = useState("")
  const [keyword, setKeyword] = useState("")
  const [analysisResult, setAnalysisResult] = useState(null)
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)

  // 模拟行业数据
  const industries = [
    "互联网/科技",
    "电子商务",
    "教育培训",
    "医疗健康",
    "金融服务",
    "餐饮服务",
    "制造业",
    "房地产",
    "文化娱乐",
    "新能源",
  ]

  const regions = ["全国", "北京", "上海", "广州", "深圳", "杭州", "成都", "武汉", "西安", "南京"]

  // 模拟分析结果
  const mockAnalysisResult = {
    marketSize: {
      total: "2,580亿元",
      growth: "+15.2%",
      forecast: "3,200亿元",
    },
    competition: {
      level: "激烈",
      majorPlayers: ["阿里巴巴", "腾讯", "字节跳动", "美团", "京东"],
      marketShare: [
        { name: "阿里巴巴", share: 28.5 },
        { name: "腾讯", share: 22.3 },
        { name: "字节跳动", share: 15.7 },
        { name: "美团", share: 12.1 },
        { name: "其他", share: 21.4 },
      ],
    },
    trends: [
      { trend: "AI技术应用", impact: "高", description: "人工智能在各行业的深度应用" },
      { trend: "用户体验优化", impact: "中", description: "注重用户体验和个性化服务" },
      { trend: "数据驱动决策", impact: "高", description: "基于大数据的精准营销和运营" },
      { trend: "生态化布局", impact: "中", description: "构建完整的商业生态系统" },
    ],
    opportunities: [
      { title: "下沉市场", description: "三四线城市用户增长潜力巨大", score: 85 },
      { title: "老龄化市场", description: "银发经济带来新的商业机会", score: 78 },
      { title: "绿色消费", description: "环保意识提升推动绿色产品需求", score: 72 },
      { title: "个性化定制", description: "消费者对个性化产品需求增长", score: 68 },
    ],
    risks: [
      { title: "政策风险", level: "高", description: "行业监管政策可能收紧" },
      { title: "技术风险", level: "中", description: "技术更新换代速度加快" },
      { title: "竞争风险", level: "高", description: "市场竞争日趋激烈" },
      { title: "资金风险", level: "中", description: "融资环境可能收紧" },
    ],
    swot: {
      strengths: ["技术优势", "用户基础", "品牌影响力", "资金实力"],
      weaknesses: ["创新能力", "国际化程度", "人才储备", "运营效率"],
      opportunities: ["新兴市场", "技术融合", "政策支持", "消费升级"],
      threats: ["监管风险", "竞争加剧", "成本上升", "技术替代"],
    },
  }

  const handleAnalyze = () => {
    if (!selectedIndustry) {
      alert("请选择行业")
      return
    }
    // 模拟分析过程
    setTimeout(() => {
      setAnalysisResult(mockAnalysisResult)
    }, 1000)
  }

  // 检查用户登录状态
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    setCurrentUser(JSON.parse(user))
    setIsLoading(false)
  }, [router])

  const getRiskColor = (level) => {
    switch (level) {
      case "高":
        return "text-red-600 bg-red-100"
      case "中":
        return "text-yellow-600 bg-yellow-100"
      case "低":
        return "text-green-600 bg-green-100"
      default:
        return "text-slate-600 bg-slate-100"
    }
  }

  const getImpactColor = (impact) => {
    switch (impact) {
      case "高":
        return "text-red-600 bg-red-100"
      case "中":
        return "text-blue-600 bg-blue-100"
      case "低":
        return "text-green-600 bg-green-100"
      default:
        return "text-slate-600 bg-slate-100"
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">验证登录状态...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 py-4">
          <div className="flex items-center space-x-4">
            <Button variant="ghost" onClick={() => router.back()}>
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
            <div className="flex items-center space-x-2">
              <TrendingUp className="w-6 h-6 text-blue-600" />
              <h1 className="text-xl font-semibold text-slate-900">市场分析工具</h1>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-6 py-8">
        {/* 分析参数设置 */}
        <Card className="mb-8">
          <CardHeader>
            <CardTitle>市场分析参数</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">目标行业</label>
                <Select value={selectedIndustry} onValueChange={setSelectedIndustry}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择行业" />
                  </SelectTrigger>
                  <SelectContent>
                    {industries.map((industry) => (
                      <SelectItem key={industry} value={industry}>
                        {industry}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">目标区域</label>
                <Select value={selectedRegion} onValueChange={setSelectedRegion}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择区域" />
                  </SelectTrigger>
                  <SelectContent>
                    {regions.map((region) => (
                      <SelectItem key={region} value={region}>
                        {region}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div>
                <label className="block text-sm font-medium text-slate-700 mb-2">关键词</label>
                <Input placeholder="输入产品/服务关键词" value={keyword} onChange={(e) => setKeyword(e.target.value)} />
              </div>

              <div className="flex items-end">
                <Button onClick={handleAnalyze} className="w-full">
                  <Search className="w-4 h-4 mr-2" />
                  开始分析
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 分析结果 */}
        {analysisResult && (
          <div className="space-y-6">
            {/* 市场概览 */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-blue-100 rounded-lg">
                      <DollarSign className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <p className="text-sm text-slate-600">市场规模</p>
                      <p className="text-2xl font-bold text-slate-900">{analysisResult.marketSize.total}</p>
                      <p className="text-sm text-green-600">{analysisResult.marketSize.growth}</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-green-100 rounded-lg">
                      <TrendingUp className="w-6 h-6 text-green-600" />
                    </div>
                    <div>
                      <p className="text-sm text-slate-600">预期增长</p>
                      <p className="text-2xl font-bold text-slate-900">{analysisResult.marketSize.forecast}</p>
                      <p className="text-sm text-slate-600">2025年预测</p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardContent className="p-6">
                  <div className="flex items-center space-x-3">
                    <div className="p-2 bg-red-100 rounded-lg">
                      <Target className="w-6 h-6 text-red-600" />
                    </div>
                    <div>
                      <p className="text-sm text-slate-600">竞争程度</p>
                      <p className="text-2xl font-bold text-slate-900">{analysisResult.competition.level}</p>
                      <p className="text-sm text-slate-600">需要差异化策略</p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 详细分析 */}
            <Tabs defaultValue="competition" className="w-full">
              <TabsList className="grid w-full grid-cols-5">
                <TabsTrigger value="competition">竞争分析</TabsTrigger>
                <TabsTrigger value="trends">市场趋势</TabsTrigger>
                <TabsTrigger value="opportunities">机会分析</TabsTrigger>
                <TabsTrigger value="risks">风险评估</TabsTrigger>
                <TabsTrigger value="swot">SWOT分析</TabsTrigger>
              </TabsList>

              <TabsContent value="competition" className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <PieChart className="w-5 h-5" />
                      <span>市场份额分布</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {analysisResult.competition.marketShare.map((company, index) => (
                        <div key={index} className="flex items-center justify-between">
                          <span className="font-medium">{company.name}</span>
                          <div className="flex items-center space-x-3">
                            <div className="w-32 bg-slate-200 rounded-full h-2">
                              <div
                                className="bg-blue-600 h-2 rounded-full"
                                style={{ width: `${company.share}%` }}
                              ></div>
                            </div>
                            <span className="text-sm font-medium w-12">{company.share}%</span>
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>主要竞争对手</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="flex flex-wrap gap-2">
                      {analysisResult.competition.majorPlayers.map((player, index) => (
                        <Badge key={index} variant="outline" className="text-sm">
                          {player}
                        </Badge>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="trends" className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <BarChart3 className="w-5 h-5" />
                      <span>市场趋势分析</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {analysisResult.trends.map((trend, index) => (
                        <div key={index} className="p-4 border border-slate-200 rounded-lg">
                          <div className="flex items-center justify-between mb-2">
                            <h4 className="font-medium text-slate-900">{trend.trend}</h4>
                            <Badge className={getImpactColor(trend.impact)}>{trend.impact}影响</Badge>
                          </div>
                          <p className="text-sm text-slate-600">{trend.description}</p>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="opportunities" className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <CheckCircle className="w-5 h-5 text-green-600" />
                      <span>市场机会</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {analysisResult.opportunities.map((opportunity, index) => (
                        <div key={index} className="p-4 border border-slate-200 rounded-lg">
                          <div className="flex items-center justify-between mb-2">
                            <h4 className="font-medium text-slate-900">{opportunity.title}</h4>
                            <div className="flex items-center space-x-2">
                              <div className="w-16 bg-slate-200 rounded-full h-2">
                                <div
                                  className="bg-green-600 h-2 rounded-full"
                                  style={{ width: `${opportunity.score}%` }}
                                ></div>
                              </div>
                              <span className="text-sm font-medium">{opportunity.score}</span>
                            </div>
                          </div>
                          <p className="text-sm text-slate-600">{opportunity.description}</p>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="risks" className="space-y-6">
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      <AlertTriangle className="w-5 h-5 text-red-600" />
                      <span>风险评估</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-4">
                      {analysisResult.risks.map((risk, index) => (
                        <div key={index} className="p-4 border border-slate-200 rounded-lg">
                          <div className="flex items-center justify-between mb-2">
                            <h4 className="font-medium text-slate-900">{risk.title}</h4>
                            <Badge className={getRiskColor(risk.level)}>{risk.level}风险</Badge>
                          </div>
                          <p className="text-sm text-slate-600">{risk.description}</p>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              </TabsContent>

              <TabsContent value="swot" className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-green-700">优势 (Strengths)</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ul className="space-y-2">
                        {analysisResult.swot.strengths.map((item, index) => (
                          <li key={index} className="flex items-center space-x-2">
                            <CheckCircle className="w-4 h-4 text-green-600" />
                            <span className="text-sm">{item}</span>
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="text-red-700">劣势 (Weaknesses)</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ul className="space-y-2">
                        {analysisResult.swot.weaknesses.map((item, index) => (
                          <li key={index} className="flex items-center space-x-2">
                            <AlertTriangle className="w-4 h-4 text-red-600" />
                            <span className="text-sm">{item}</span>
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="text-blue-700">机会 (Opportunities)</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ul className="space-y-2">
                        {analysisResult.swot.opportunities.map((item, index) => (
                          <li key={index} className="flex items-center space-x-2">
                            <Target className="w-4 h-4 text-blue-600" />
                            <span className="text-sm">{item}</span>
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="text-yellow-700">威胁 (Threats)</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <ul className="space-y-2">
                        {analysisResult.swot.threats.map((item, index) => (
                          <li key={index} className="flex items-center space-x-2">
                            <AlertTriangle className="w-4 h-4 text-yellow-600" />
                            <span className="text-sm">{item}</span>
                          </li>
                        ))}
                      </ul>
                    </CardContent>
                  </Card>
                </div>
              </TabsContent>
            </Tabs>
          </div>
        )}

        {/* 使用说明 */}
        {!analysisResult && (
          <Card className="bg-blue-50 border-blue-200">
            <CardContent className="p-6">
              <h3 className="font-semibold text-blue-900 mb-3">如何使用市场分析工具</h3>
              <div className="space-y-2 text-sm text-blue-800">
                <p>1. 选择您要分析的目标行业</p>
                <p>2. 选择目标区域（可选）</p>
                <p>3. 输入相关关键词（可选）</p>
                <p>4. 点击"开始分析"获取详细的市场分析报告</p>
              </div>
              <div className="mt-4 p-3 bg-blue-100 rounded-lg">
                <p className="text-sm text-blue-900">
                  <strong>提示：</strong>
                  分析结果基于公开数据和行业报告，建议结合实地调研进行验证。
                </p>
              </div>
            </CardContent>
          </Card>
        )}
      </main>
    </div>
  )
}
